import { Form, Space } from 'antd';
import { ComponentInfo, EditorComponentType } from '../components/editor';
import { componentConfigList } from '@/components/editor';
import FormItem from '@/components/editor/FormItem';

export function getParagraphList(text: string = '') {
  return text?.split('\n').map((item, index) => (
    <span key={index}>
      {index > 0 && <br></br>}
      {item}
    </span>
  ));
}

// form表单UI
export function formUI(form: any, isLocked?: boolean) {
  const list = form.items.map((item: any) => {
    const { label, name, formItem, error } = item;
    return (
      <FormItem label={label} key={name} error={error}>
        {formItem}
      </FormItem>
    );
  });

  return (
    <Form disabled={isLocked} layout="vertical">
      <Space size={32} direction="vertical">
        {list}
      </Space>
    </Form>
  );
}

export function getComponentInfo(
  selectedId: string,
  componentList: ComponentInfo[]
) {
  return componentList.find((info) => info.fe_id === selectedId);
}

export function getComponentConfig(type?: EditorComponentType) {
  return componentConfigList.find((item) => item.type === type);
}

export function getForm(componentInfo?: ComponentInfo) {
  if (!componentInfo) {
    return <div style={{ textAlign: 'center' }}>未选中组件</div>;
  }

  const { type } = componentInfo;
  const componentConfig = getComponentConfig(type);
  if (!componentConfig) return null;

  return <componentConfig.Form />;
}

export function getComponet(componentInfo: ComponentInfo) {
  const { type, props } = componentInfo;
  const componentConfig = getComponentConfig(type);
  if (!componentConfig) return null;

  return <componentConfig.Component {...props} />;
}

export function getNextSelectedId(selectId: string, list: ComponentInfo[]) {
  list = list.filter((info) => info.isHidden === false);
  const index = list.findIndex((info) => info.fe_id === selectId);
  let next = list[index + 1];
  if (list.length === index + 1) {
    next = list[index - 1];
  }
  return next?.fe_id || '';
}
